//
//  CustomRecommendsView.swift
//  MyCloset
//
//  Created by 牟好好 on 2024/11/12.
//

import SwiftUI

struct CustomRecommendsView: View {
    @Environment(\.dismiss) var dismiss
    @EnvironmentObject var vm: ClothStylesViewModel
    @State private var selectedTab = "plus.app"
    @State private var isSelectedColors = false
    @State private var selectedItems: [String] = []
    @State private var selectedIndex: Int = 0
    @State private var typeSelectedGroup: [Int] = []
    @State private var isShowTrash: Bool = false
    @State private var isScrollTop = false
    @State private var isScrollBottom = false
    @Namespace var topID
    @Namespace var bottomID
    
    var body: some View {
        VStack {
            TopNavigationBar(title: "修改搭配") {
                dismiss()
            }
            
            CustomTopBar(selectedTab: $selectedTab)
            
            // 顶部固定部分
            if selectedTab == "plus.app" {
                CustomTopChooseBar(isSelectedColors: $isSelectedColors) {
                    resetParams()
                }
                if !isSelectedColors {
                    CustomTopTypeTabBar(selectedIndex: $selectedIndex, items: clothTypes)
                }
            }
            
            let columns: [GridItem] = Array(repeating: .init(.flexible()), count: 3)
            
            if selectedTab == "plus.app" {
                ScrollView(.vertical, showsIndicators: false) {
                    if isSelectedColors {
                        LazyVGrid(columns: columns, spacing: 10) {
                            ForEach(clothColors, id: \.self) { color in
                                ColorButton(isChecked: selectedItems.contains(color), color: color) {
                                    selectColor(color: color)
                                }
                            }
                        }
                        .frame(maxWidth: boundsWidth * 0.8)
                    } else {
                        let arrays = [vm.shangzhuang, vm.xiazhuang, vm.waitao, vm.xiezi, vm.maozi]
                        
                        LazyVGrid(columns: columns, spacing: 10) {
                            ForEach(arrays[selectedIndex], id: \.self) { item in
                                CustomStyleView(item: item, isChoosed: selectedItems.contains(item)) {
                                    selectItem(item: item, index: selectedIndex)
                                }
                            }
                        }
                        .padding(.horizontal, boundsWidth * 0.1)
                    }
                }
                Button(action: {
                    if selectedItems.count == 2 {
                        vm.addCombination([selectedItems[0], selectedItems[1]])
                        resetParams()
                    }
                }, label: {
                    Text("保存")
                        .padding(.vertical, 10)
                        .foregroundStyle(.white)
                        .frame(maxWidth: boundsWidth * 0.5)
                        .background(selectedItems.count == 2 ? .blue : .gray)
                        .cornerRadius(12)
                })
                .disabled(selectedItems.count != 2)
                
                Text(selectedItems.joined(separator: ","))
                
                Spacer(minLength: safeAreaBottom)
            } else {
                DeleteCombinationsTopView(isShowTrash: $isShowTrash, reset: {
                    vm.recommendedCombinations = recommendedCombinationsBase
                })
                
                ZStack(alignment: .bottomTrailing) {
                    ScrollViewReader { proxy in
                        ScrollView(.vertical, showsIndicators: false) {
                            Spacer(minLength: 0)
                                .id(topID)
                            
                            VStack(spacing: 15) {
                                // 推荐搭配列表
                                ForEach(vm.recommendedCombinations, id: \.self) { item in
                                        // 与颜色数组有交集即展示为色块
                                    CustomRecommendsRow(item1: item[0], item2: item[1], isColor: !Set(item).isDisjoint(with: Set(clothColors)), isShowTrash: $isShowTrash) {
                                        vm.removeCombination(item)
                                    }
                                    .animation(.linear(duration: 0.2), value: isShowTrash)
                                }
                            }
                            .padding(.all)
                            Spacer(minLength: safeAreaBottom)
                                .id(bottomID)
                        }
                        .onChange(of: isScrollTop) { _, _ in
                            proxy.scrollTo(topID)
                        }
                        .onChange(of: isScrollBottom) { _, _ in
                            proxy.scrollTo(bottomID)
                        }
                    }
                    
                    NavigateButtons(isScrollTop: $isScrollTop, isScrollBottom: $isScrollBottom)
                }
                .frame(maxWidth: .infinity)
            }
        }
        .onChange(of: selectedTab) { _, _ in resetParams() }
        .onChange(of: isSelectedColors) { _, _ in resetParams() }
        .onDisappear { resetParams() }
        .foregroundStyle(.accent)
        .padding(.top, safeAreaTop)
        .ignoresSafeArea(.all, edges: .all)
    }
    
    func selectItem(item: String, index: Int) {
        // 包含该项
        if let i = selectedItems.firstIndex(where: { $0 == item }) {
            typeSelectedGroup.removeAll(where: { $0 == index })
            selectedItems.remove(at: i)
        } else {
            // 包含同类型服饰或选中项达到上限
            guard !typeSelectedGroup.contains(index) && typeSelectedGroup.count < 2 else { return }
            typeSelectedGroup.append(index)
            selectedItems.append(item)
        }
    }
    
    func selectColor(color: String) {
        if selectedItems.contains(color) {
            selectedItems.removeAll(where: { $0 == color })
        } else if selectedItems.count < 2 {
            selectedItems.append(color)
        }
    }
    
    func resetParams() {
        typeSelectedGroup = []
        selectedItems = []
    }
}

#Preview {
    CustomRecommendsView()
        .environmentObject(ClothStylesViewModel())
}

#Preview {
    CustomRecommendsView()
        .environmentObject(ClothStylesViewModel())
        .preferredColorScheme(.dark)
}
